import { messages } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Button, Badge, Popover, Icon } from 'antd';
import ResizeTable from 'components/resize-table'
import SlideFrame from "components/slide-frame";
import 'styles/financial-management/supplier-management/supplier-bank-account.scss'
import NewCustomerBank from 'containers/customer-info-maintenance/new-customer-bank'
import menuRoute from 'routes/menuRoute'
import BasicInfo from 'components/basic-info'
import CustomerInfoMaintenanceService from 'containers/customer-info-maintenance/customer-info-maintenance.service'
import moment from "moment"

class CustomerBankAccount extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tenant: window.location.href.indexOf('tenant') !== -1,
      type: window.location.href.indexOf('tenant') !== -1 ? 'tenant' : 'company',
      loading: false,
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
      },
      infoList: [
        {
          type: 'input', id: 'customerTypeName',
          disabled: true,
          label: messages('customer-info-maintenance.key1')/*客户类型*/
        }, /*供应商类型*/
        {
          type: 'input', id: 'customerCode',
          disabled: true,
          label: messages('customer-info-maintenance.key2')/*客户代码*/
        }, /*供应商代码*/
        {
          type: 'input', id: 'customerName',
          disabled: true,
          label: messages('customer-info-maintenance.key3')/*客户名称*/
        }, /*供应商名称*/
        {
          type: 'switch',
          id: 'enabled',
          defaultValue: true,
          label: messages('common.column.status') /*状态*/
        },
      ],
      columns: [
        {
          title: messages('financial-management.key337'/*序号*/),
          dataIndex: 'index', width: '5%',
          render: (text, record, index) => <Popover content={index + 1}>{index + 1}</Popover>
        },
        {
          title: messages('financial-management.key302'/*银行代码*/), key: "bankCode", dataIndex: 'bankCode',
          render: text => <Popover content={text}>{text}</Popover>
        },
        {
          title: messages('financial-management.key303'/*银行名称*/), key: "bankName", dataIndex: 'bankName',
          render: text => <Popover content={text}>{text}</Popover>
        },
        {
          title: messages('financial-management.key319'/*银行账号*/), key: "bankAccount", dataIndex: 'bankAccount',
          render: text => <Popover content={text}>{text}</Popover>
        },
        {
          title: messages('financial-management.key338'/*银行户名*/), key: "bankNumberName", dataIndex: 'bankNumberName',
          render: text => <Popover content={text}>{text ? text : "-"}</Popover>
        },
        {
          title: messages('customer-info-maintenance.key7')/*账户标志*/, key: "bankAccountFlag", dataIndex: 'bankAccountFlag',
          render: text => <Popover content={text === "02" ? messages('customer-info-maintenance.key8')/*对公*/ : messages('customer-info-maintenance.key9')/*对私*/}>{text === "02" ? messages('customer-info-maintenance.key8')/*对公*/ : messages('customer-info-maintenance.key9')/*对私*/}</Popover>
        },
        {
          title: messages('financial-management.key339'/*最近更新时间*/), key: "lastModifiedDate", dataIndex: 'lastModifiedDate',
          render: text =>
            <span>
              <Popover content={text ? moment(new Date(text)).format("YYYY-MM-DD") : "-"}>
                {text ? moment(new Date(text)).format("YYYY-MM-DD") : "-"}
              </Popover>
            </span>
        },
        {
          title: messages('common.column.status'), key: "enabled", dataIndex: 'enabled',
          render: value => (
            <Badge status={value ? 'success' : 'error'}
                   text={value ? messages("common.status.enable") : messages("common.status.disable")} />)
        },
        {
          title: messages('financial-management.key315'/*主账户*/), key: "primaryFlag", dataIndex: 'primaryFlag',
          render: text => <span>{text ? messages('common.yes')/*是*/ : messages('common.no')/*否*/}</span>
        },
        {
          title: messages('common.operation'), key: "operate", dataIndex: 'operate', width: '80px',
          render: (text, record, index) => (
            <span>
              {/*如果是 TENANT且公司模式 就不能编辑*/}
              {
                !(!this.state.tenant && props.params.source === "TENANT") && this.checkNewAuth() ?
                <a onClick={(e) => this.handleUpdate(e, record, index)}>{messages('common.edit')}</a>
                : messages("common.edit")
              }
            </span>)
        },
      ],
      record: {},
      visible: false,
      id: null,
      data: [],
    };
  }

  componentWillMount() {
   this.getCustomerDetail();
   this.getBankAccountList();
  }

  componentWillReceiveProps(nextProps){
    if(this.props.location.pathname !== nextProps.location.pathname){
      let tenant = nextProps.location.pathname.indexOf('tenant') !== -1;
      let type = tenant ? 'tenant' : 'company';
      this.setState({
        tenant,
        type,
      }, () => {
        this.getCustomerDetail();
        this.getBankAccountList();
      });
    }
  }

  //获取客户信息详情
  getCustomerDetail = () => {
    CustomerInfoMaintenanceService.getCustomerDetail(this.props.params.id)
      .then(res => {
          this.setState({
            record: res.data,
          })
        }
      ).catch(err => {
    })
  };

  //获取已分配公司列表
  getBankAccountList = () => {
    const {pagination, tenant} = this.state;
    this.setState({loading: true});
    let params = {
      page: pagination.page,
      size: pagination.pageSize,
    };
    if(tenant){
      params.roleType = 'TENANT';
    }
    CustomerInfoMaintenanceService.getBankAccountList(this.props.params.id, params)
      .then(res => {
        this.setState({
          loading: false,
          data: res.data,
          pagination: {
            current: pagination.page + 1,
            total: Number(res.headers['x-total-count']) || 0,
            onChange: this.onChangePager,
          }
        })
      }
    ).catch(err => {
      this.setState({
        loading: false,
      });
    })
  };


  //分页点击
  onChangePager = (pagination) => {
    let temp = this.state.pagination;
    temp.page = pagination.current-1;
    temp.current = pagination.current;
    this.setState({
      pagination: temp
    }, () => {
      this.getBankAccountList();
    })
  };

  //新建侧滑
  handleCreate = () => {
    this.setState({
      visible: true,
      id: null,
    })
  };

  handleUpdate = (e, record) => {
    e.stopPropagation();
    this.setState({
      id: record.id,
      visible: true,
    })
  };

  afterClose = (params) => {
    this.setState({
      id: null,
      visible: false,
    });
    this.getBankAccountList();
  };

  //返回
  handleBack = () => {
    const {type} = this.state;
    this.context.router.push(menuRoute.getRouteItem(`customer-${type}-maintenance`, 'key').url)
  };

  render() {
    const { loading, infoList, data, pagination, columns, tenant, record, visible, id} = this.state;
    return (
      <div className="supplier-bank-account">
        <BasicInfo
          infoList={infoList}
          infoData={record}
          isHideEditBtn={true}
        />
        <div className="table-header">
          <div className="table-header-title">
            {messages('common.total', { total: `${pagination.total}` })}
          </div>  {/*共搜索到*条数据*/}
          <div className="table-header-buttons">
            {
              this.checkNewAuth() &&
            <Button type="primary" disabled={(!tenant && this.props.params.source === "TENANT")} onClick={this.handleCreate}>
              {/*新 建*/}
              {messages('common.create')}
            </Button>}
          </div>
        </div>
        <ResizeTable
          loading={loading}
          dataSource={data}
          pagination={pagination}
          columns={columns}
          onChange={this.onChangePager}
          bordered
          rowKey="id"
          size="middle" />
        <a style={{ fontSize: '14px', paddingBottom: '20px' }}
           onClick={this.handleBack}><Icon type="rollback" style={{ marginRight: '5px' }} />
          {messages("common.back")}
        </a>

        <SlideFrame
          isShowCloseBtn={false}
          title={id ? messages('customer-info-maintenance.key10')/*编辑客户银行账户*/ : messages('customer-info-maintenance.key11')/*新建客户银行账户*/}
          show={visible}
          content={NewCustomerBank}
          afterClose={this.afterClose}
          params={{id: id, customerId: this.props.params.id, visible: visible}}/>
      </div>
    )
  }
}

CustomerBankAccount.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    main: state.main
  }
}

export default connect(mapStateToProps)(CustomerBankAccount);
